<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
	<th:block th:include="include :: header('修改（报价单）')" />
	<th:block th:include="include :: datetimepicker-css" />
	<th:block th:include="include :: bootstrap-editable-css" />
</head>
<body class="white-bg">
	<div class="wrapper wrapper-content animated fadeInRight ibox-content">
		<form class="form-horizontal m" id="form-order-edit" th:object="${crmOrderPrice}">
			<h4 class="form-header h4">基本信息</h4>
			<input name="orderId" th:field="*{orderId}" type="hidden"> 
			<input name="customerId" type="hidden" id="customerId" />
			<div class="row">
				<div class="col-sm-6">
					<div class="form-group">
						<label class="col-sm-4 control-label is-required">报价客户：</label>
						<div class="col-sm-8">
							<div class="input-group">
	                    		<input name="customerName" onclick="selectCustomer()" th:field="*{customer.customerName}" class="form-control" type="text" placeholder="请选择报价客户 " id="customerName" required readonly>
								<span class="input-group-addon"><i class="fa fa-search"></i></span>
	                    	</div>
						</div>
					</div>
				</div>
				<div class="col-sm-6">
					<div class="form-group">
						<label class="col-sm-4 control-label is-required">主题：</label>
						<div class="col-sm-8">
							<input name="orderName" th:field="*{orderName}" class="form-control" type="text" required>
						</div>
					</div>
				</div>
			</div>
			
			<div class="row">
				<div class="col-sm-6">
					<div class="form-group">
						<label class="col-sm-4 control-label is-required">报价总额：</label>
						<div class="col-sm-6">
							<input name="totalPrice" th:field="*{totalPrice}" class="form-control" type="text" required>
							<input name="costPrice" th:field="*{costPrice}" class="form-control" type="hidden">
						</div>
						<div class="col-sm-2">
							<i class="fa fa fa-cny"><a href="javascript:autoCaculate();">自动计算</a></i>
						</div>
					</div>
				</div>
				<div class="col-sm-6">
					<div class="form-group">    
		                <label class="col-sm-4 control-label">报价人：</label>
		                <div class="col-sm-8">
		                    <input name="prcieBy" th:field="*{prcieBy}" class="form-control" type="text">
		                </div>
		            </div>
				</div>
			</div>
			<div class="row">
				<div class="col-sm-6">
					<div class="form-group">    
		                <label class="col-sm-4 control-label">报价时间：</label>
		                <div class="col-sm-8">
		                    <div class="input-group date">
		                        <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
		                        <input name="prcieEndDate" th:value="${#dates.format(crmOrderPrice.prcieEndDate, 'yyyy-MM-dd')}" class="form-control" placeholder="yyyy-MM-dd" type="text">
		                    </div>
		                </div>
		            </div>
				</div>
				<div class="col-sm-6">
					<div class="form-group">    
		                <label class="col-sm-4 control-label is-required">报价有效截止时间：</label>
		                <div class="col-sm-8">
		                    <div class="input-group date">
		                        <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
		                        <input name="prcieEndDate" th:value="${#dates.format(crmOrderPrice.prcieEndDate, 'yyyy-MM-dd')}" class="form-control" placeholder="yyyy-MM-dd" type="text" required>
		                    </div>
		                </div>
            		</div>
				</div>				
			</div>
			<div class="row">
				<div class="col-sm-12">
					<div class="form-group">
						<label class="col-xs-2 control-label">备注：</label>
						<div class="col-xs-10">
							<textarea name="remark" maxlength="500" class="form-control" rows="3">[[*{remark}]]</textarea>
						</div>
					</div>
				</div>
			</div>
		</form>
		<h4 class="form-header h4">产品信息</h4>
		<div class="container-div">
			<div class="row">
				<div class="btn-group-sm" id="toolbarProduct" role="group">
					<a class="btn btn-success" onclick="addProduct();"> <i
						class="fa fa-plus"></i> 添加
					</a>
				</div>
				<div class="col-sm-12 select-table table-striped">
					<table id="bootstrap-table"></table>
				</div>
			</div>
		</div>
	</div>
	<div class="row">
        <div class="col-sm-offset-5 col-sm-10">
        	<button type="button" class="btn btn-sm btn-primary" onclick="submit()" shiro:hasPermission="crm:orderPrice:submit"><i class="fa fa-location-arrow"></i>提 交</button>&nbsp;
            <button type="button" class="btn btn-sm btn-primary" onclick="submitHandler()"><i class="fa fa-check"></i>保 存</button>&nbsp;
            <button type="button" class="btn btn-sm btn-danger" onclick="closeItem()"><i class="fa fa-reply-all"></i>关 闭 </button>
        </div>
    </div>
	<th:block th:include="include :: footer" />
	<th:block th:include="include :: datetimepicker-js" />
	<th:block th:include="include :: bootstrap-table-editable-js" />
	<script th:inline="javascript">
		var productCategoryDatas = [[${@dict.getType('product_category')}]];
		var orderProductStatusDatas = [[${@dict.getType('order_product_status')}]];
		var prefix = ctx + "crm/orderPrice";
		var prefixProduct = ctx + "crm/product";
		var prefixOrderPriceProduct =  ctx + "crm/orderPriceProduct";
		var orderId=[[${orderId}]];
		
		$("#form-order-edit").validate({
			focusCleanup : true
		});
		
		$(function() {
            var options = {
                url: prefixOrderPriceProduct + "/listAll",
                removeUrl: prefixOrderPriceProduct + "/remove",
                showSearch: false,
		        showRefresh: false,
		        showToggle: false,
		        showColumns: false,
		        showPageGo: true,
		        onEditableSave: onEditableSave,
                modalName: "关联产品信息",
                queryParams : {
                    orderId:orderId
				},
                columns: [                
                {
                    field : 'orderProductId', 
                    title : '订单产品ID',
                    visible: false
                },
		        {
                    title: "序号",
                    formatter: function (value, row, index) {
                 	    return $.table.serialNumber(index);
                    }
                },
                {
                    field : 'orderId', 
                    title : '订单id',
                    visible: false
                },
                {
                    field : 'productId', 
                    title : '产品id',
                    visible: false
                },
                {
                    field : 'productName', 
                    title : '产品名称'
                },
                {
                    field : 'sellPrice', 
                    title : '销售单价',
					editable : {
						type : 'text',
						title : '销售单价',
						emptytext : "【销售单价】为空",
						validate : function(value) {
							if (value.length == 0) {
								return '销售单价不能为空';
							}
							if (!isNumber(value)) {
						        return '销售单价必须为数字';
						    }	
						}
					}
                },
                {
                    field : 'productCount', 
                    title : '报价数量',
					editable : {
						type : 'text',
						title : '订购数量',
						emptytext : "【订购数量】为空",
						validate : function(value) {
							if (value.length == 0) {
								return '订购数量不能为空';
							}
							if (!(isNumber(value) && value % 1 === 0)) {
						        return '订购数量必须为数字';
						    }	
						}
					}
                },
                {
                    field : 'product.salePrice', 
                    title : '原价'
                },
                {
                    field : 'discount', 
                    title : '折扣',
					editable : {
						type : 'text',
						title : '折扣（1-10之间）',
						emptytext : "【折扣】为空",
						validate : function(value) {
							if (value.length == 0) {
								return '折扣不能为空';
							}
							if (!isNumber(value)) {
						        return '折扣必须为【1-10】之间的数字';
						    }	
							if (parseInt(value)>10||parseInt(value)<0) {
						        return '折扣必须为【1-10】之间的数字';
						    }
						}
					}
                },
                {
                    field : 'realPrice', 
                    title : '实际价格'
                },
				{
				    title: '图片',
				    formatter: function(value, row, index) {
				    	return $.table.imageView(row.product.productImage);
				    }
				},
                {
                    field : 'product.productCategory', 
                    title : '产品类别',
                    formatter: function(value, row, index) {
                       return $.table.selectDictLabel(productCategoryDatas, value);
                    },
		            sortable: true
                },
                {
                    field : 'orderProductStatus', 
                    title : '状态',
                    formatter: function(value, row, index) {
                       return $.table.selectDictLabel(orderProductStatusDatas, value);
                    },
                    visible: false
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function(value, row, index) {
                        var actions = [];
                        //actions.push('<a class="btn btn-success btn-xs '  + '" href="javascript:void(0)" onclick="$.operate.edit(\'' + row.orderProductId + '\')"><i class="fa fa-edit"></i>编辑</a> ');
                        actions.push('<a class="btn btn-danger btn-xs '  + '" href="javascript:void(0)" onclick="$.operate.remove(\'' + row.orderProductId + '\')"><i class="fa fa-remove"></i>删除</a>');
                        return actions.join('');
                    }
                }]
            };
            $.table.init(options);
        });
		
		/* function queryParams(params) {
			debugger;
            //var search = $.table.queryParams(params);
            search.orderType = '10';
            return search;
        } */
		
		function onEditableSave (field, row, oldValue, $el) {
        	//alert("字段名：" + field + "，当前值：" + row[field]  + "，旧值：" + oldValue);
        	if(field=="productCount"){//订购数量
        		var data = { "orderPriceProductId": row.orderProductId, "productCount": row[field]};
    			$.operate.post(prefixOrderPriceProduct + "/updateOrderPriceProductCount", data);
        	}
        	else if(field=="sellPrice"){//销售价格
        		var data = { "orderPriceProductId": row.orderProductId, "sellPrice": row[field]};
    			$.operate.post(prefixOrderPriceProduct + "/updateOrderPriceSellPrice", data);
        	}
			else if(field=="discount"){//折扣
				var data = { "orderPriceProductId": row.orderProductId, "discount": row[field]};
    			$.operate.post(prefixOrderPriceProduct + "/updateOrderPriceDiscount", data);
        	}
        }
        
        function submit() {
			if ($.validate.form()) {
				$.modal.confirm("确认提交吗？", function() {
					$.operate.saveTab(prefix + "/submit", $('#form-order-edit').serialize());
	        	});
			}
		}

		function submitHandler() {
			if ($.validate.form()) {
				$.operate.saveTab(prefix + "/edit", $('#form-order-edit')
						.serialize());
			}
		}

		$("input[name='prcieDate']").datetimepicker({
			format : "yyyy-mm-dd",
			minView : "month",
			autoclose : true
		});
		
		$("input[name='prcieEndDate']").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        });
		
		/* 自动计算 */
		function autoCaculate(){
			var data = $("#" + table.options.id).bootstrapTable('getData');
			if (data.length == 0) {
       			$.modal.alertWarning("请添加产品后计算！");
       			return;
       		}
			var orderId= [[${orderId}]];
			$.ajax({
	            url: prefixOrderPriceProduct + "/selectOrderPrice",
	            data: {
					"orderPriceId" : orderId
				},
	            type: "post",
	            success: function(result) {
	            	if (result.code == 0) {
	            		$("#totalPrice").val(result.data.totalPrice);
	            		$("#costPrice").val(result.data.costPrice);
	            		$.modal.msgSuccess(result.msg);
	            	} else {
	            		$.modal.msgError(result.msg);
	            	}
	            },
				error : function(e) {
					$.modal.msgError("系统异常");
				}
	        })
		}
		
		/* 报价单管理-修改-选择产品  */
		function addProduct()
		{
			var orderId= [[${orderId}]];
			$.modal.open('选择报价单产品', prefixProduct + '/selectOrderPriceProduct/'+orderId);
		}
		
		/* 订单管理-修改-选择客户  */
	    function selectCustomer() {
	    	var url = ctx + "crm/customer/selectCustomer";
	   		$.modal.open("选择客户", url);
		}
			
	    function isNumber(val){
	        var regPos = /^\d+(\.\d+)?$/; //非负浮点数
	        if(regPos.test(val)){
	            return true;
	        }else{
	            return false;
	        }
	    }
	</script>
</body>
</html>